package com.ly.system.service.impl;

import cn.hutool.core.net.NetUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.common.core.bean.R;
import com.ly.system.system.bean.dto.IdsDTO;
import com.ly.system.system.bean.entity.SysRolePermission;
import com.ly.system.mapper.SysRolePermissionMapper;
import com.ly.system.service.ISysRolePermissionService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色权限-服务
 *
 * @author jeecg
 * @since 2018-12-21
 */
@Service
public class SysRolePermissionServiceImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements ISysRolePermissionService {

    @Override
    public R getAuthByRoleId(String roleId) {
        List<SysRolePermission> list = this.list(
                new LambdaQueryWrapper<SysRolePermission>()
                        .eq(SysRolePermission::getRoleId, roleId)
        );
        List<String> authIdList = list.stream().map(n -> n.getPermissionId()).collect(Collectors.toList());
        return R.ok(authIdList);
    }

    @Override
    public R saveRoleAuth(IdsDTO dto) {
        String id = dto.getId();
        List<String> ids = dto.getIds();
        String ip = NetUtil.getLocalhostStr();
        this.remove(
                new LambdaQueryWrapper<SysRolePermission>()
                        .in(SysRolePermission::getRoleId, id)
        );
        List<SysRolePermission> list = ids.stream()
                .map(n -> new SysRolePermission(id, n, ip))
                .collect(Collectors.toList());
        boolean flag = this.saveBatch(list);
        return flag ? R.ok(true, "创建成功") : R.fail("创建失败");
    }
}
